package com.example.demo.controller;

import com.example.demo.model.common.ApiResult;
import com.example.demo.model.entity.DeviceConfig;
import com.example.demo.service.DeviceConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/device/config")
@Slf4j
public class DeviceConfigController {

    @Autowired
    private DeviceConfigService deviceConfigService;

    @GetMapping("/{imei}")
    public ApiResult<DeviceConfig> getConfig(@PathVariable String imei, @RequestHeader("X-WX-OPENID") String openid) {
        log.info("Received GET request for imei: {}, openid: {}", imei, openid);
        try {
            DeviceConfig config = deviceConfigService.getByImei(imei);
            ApiResult<DeviceConfig> result = ApiResult.success(config);
            log.info("Returning config data to frontend: {}", result);
            return result;
        } catch (Exception e) {
            log.error("Failed to get device config", e);
            return ApiResult.error("获取配置失败");
        }
    }

    @PostMapping("/save")
    public ApiResult<Void> saveConfig(@RequestBody DeviceConfig config, @RequestHeader("X-WX-OPENID") String openid) {
        log.info("Received POST request to save config: {}, openid: {}", config, openid);
        try {
            boolean success = deviceConfigService.saveOrUpdateConfig(config, openid);
            ApiResult<Void> result = success ? ApiResult.success() : ApiResult.error("保存失败");
            log.info("Returning save result to frontend: {}", result);
            return result;
        } catch (Exception e) {
            log.error("Failed to save device config", e);
            return ApiResult.error("保存失败");
        }
    }
}